package com.pan.structual.adapter.tool;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

public enum AdapterXmlUtils {
    INSTANCE;
    private Document xmlDoc;
    private Element rootElement;
    {
        try {
            xmlDoc = DocumentBuilderFactory
                    .newInstance()
                    .newDocumentBuilder()
                    .parse(new File("src\\main\\java\\com\\pan\\structual\\adapter\\config.xml"));
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
        rootElement = xmlDoc.getDocumentElement();
        rootElement.normalize();

    }


    public Element getElement(String nodeName){
        NodeList elementsByTagName = rootElement.getElementsByTagName(nodeName);
        return (Element) elementsByTagName.item(0);
    }

    public String getNodeValue(String nodeName){
        return this.getElement(nodeName).getTextContent().strip();
    }

    /**
     *
     * @param nodeName
     * @return
     */
    public Object getObj(String nodeName){
        String className = this.getNodeValue(nodeName);
        try {
            Object o = Class.forName(className).getConstructor().newInstance();
            return o;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
